package com.fans.admin.quartz.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoaderListener;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.fans.admin.quartz.constant.QtzConstant;
import com.fans.admin.quartz.constant.QtzConstant.ScheduleStatusEnum;
import com.fans.admin.quartz.entity.ScheduleJob;
import com.fans.admin.quartz.service.IScheduleJobService;
import com.fans.admin.quartz.util.ExceptionUtil;
import com.fans.admin.quartz.util.QuartzUtil;
import com.fans.common.utils.SpringUtil;



/**
 * @ClassName: QuartzServletContextListener
 * @Description: 系统启动时，启动任务信息(该类目前没用到)
 * @author fanhaohao
 * @date 2020年1月16日 下午3:51:27
 */
public class QuartzServletContextListener extends ContextLoaderListener implements ServletContextListener {

	private Logger logger = LoggerFactory.getLogger(QuartzServletContextListener.class);
	
	private IScheduleJobService scheduleJobService;
	
	private Scheduler scheduler;
	
	public void initBean() {
		if(null == scheduleJobService) {
			scheduleJobService = SpringUtil.getBean(IScheduleJobService.class);
		}
		if(null == scheduler) {
			scheduler = SpringUtil.getBean("baseQuartzScheduler");
		}
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		/**
		 * 注：使用quartz分布式集群时，系统停止时，不能关闭任务信息；否则，否则集群中的任务都会被关闭
		 */
		/*try {
			initBean();
			QuartzUtil.deleteAllScheduleJob(scheduler);
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		initBean();
		
		/**
		 * 注：使用quartz分布式集群时，其实只有在第一次部署时，需要执行此方法，之后都不再需要；当然如果操作系统重启，则需要；
		 */
		List<ScheduleJob> jobs = scheduleJobService.findList(null);
		if(CollectionUtils.isNotEmpty(jobs)) {
			for (ScheduleJob scheduleJob : jobs) {
				//如果是启用状态
				if(ScheduleStatusEnum.USABLE.equals(scheduleJob.getJobStatus())) {
					try {
						QuartzUtil.createScheduleJob(scheduler, scheduleJob, true);
						if (QtzConstant.ScheduleStatus.NORMAL.getValue().equals(scheduleJob.getStatus())) {
							QuartzUtil.resumeScheduleJob(scheduler, scheduleJob);// 恢复
						} else {
							QuartzUtil.pauseScheduleJob(scheduler, scheduleJob);// 暂停
						}
					} catch (SchedulerException e) {
						logger.error(
								"启动任务【" + scheduleJob.getJobName() + "】失败！\n" + ExceptionUtil.getStackTraceAsString(e));
					}
				} else {
					try {
						QuartzUtil.deleteScheduleJob(scheduler, scheduleJob);
					} catch (SchedulerException e) {
						logger.error("删除禁用任务【" + scheduleJob.getJobName() + "】失败！\n"
								+ ExceptionUtil.getStackTraceAsString(e));
					}
				}
			}
		}
	}

}
